package com.mpsc.sharding.interceptor;


import com.mpsc.api.bean.UserInfoEntity;
import com.mpsc.sharding.util.CacheHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 平台用户上下文缓存设置类
 */
//@Component
public class UserContextInterceptor //implements HandlerInterceptor
{

    /**
     * 账户应用id
     */
    @Value("${sharding.account.appId:fbp-account}")
    private String accountAppId;

    /**
     * 账户应用code
     */
    @Value("${sharding.account.app1Code:005}")
    public String accountAppCode;

    //@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 从平台获取用户上下文信息
            UserInfoEntity userContextDTO = new UserInfoEntity();
            String appId = request.getHeader("");
            if (StringUtils.isNotBlank(appId)) {
                if (appId.equalsIgnoreCase(accountAppId)) {
                    // 是账户的应用在请求工作流
//                   userContextDTO.setAppCode(accountAppCode);
                }
            }
            CacheHolder.set(CacheHolder.CONTEXT_USER_INFO, userContextDTO);
        } catch (Exception e) {
            throw new RuntimeException("设置用户上下文信息失败", e);
        }

        return true;
    }

    //@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) {
        CacheHolder.remove();
    }

}
